<script setup lang="ts">
import { ref, type Ref, onMounted, onBeforeUnmount, reactive } from 'vue'
import { PPTListItem } from '@/models/ai-ppt'
import PptHeader from '@/views/ai-pptx/PptHeader.vue'
import { httpGetPptData, httpSavePptData, httpTextToImg } from '@/api/ai-ppt'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import useUserStore from '@/stores/user'
import { md5 } from 'js-md5'
import AIToImg from '@/icons/AIToImg.vue'
import { Picture as IconPicture } from '@element-plus/icons-vue'

const route = useRoute()
const userStore = useUserStore()
const id: Ref<number> = ref(0)
const pptData: Ref<PPTListItem> = ref(null)
const headerTitle: Ref<string> = ref('')
const loading: Ref<boolean> = ref(false)
const pptIstUrl = import.meta.env.VITE_PPT_IST_URL
const isFullScreen = ref<boolean>(false)
const formData = reactive<Record<string, string>>({
  url: '',
  name: '',
})
const visible = ref<boolean>(false)
const rules = {
  url: [{ message: '请输入文本内容', trigger: ['change', 'blur'] }],
}
const base64 = ref<string>('')
const listenOnSave = async (event: MessageEvent) => {
  if (!event.data) {
    return
  }
  if (event.data.ppt_full_screen !== undefined) {
    isFullScreen.value = event.data.ppt_full_screen
    return
  }
  const { data, images } = event.data
  pptData.value.content = data
  httpSavePptData(id.value, headerTitle.value, JSON.stringify(images), data)
    .then(() => {})
    .catch(() => {})
}

onMounted(() => {
  const queryId = parseInt(route.query.id + '')
  if (isNaN(queryId) || !queryId) {
    ElMessage.error('参数错误')
    history.back()
  }
  id.value = queryId
  window.addEventListener('message', listenOnSave)
  getPptData()
})

onBeforeUnmount(() => {
  window.removeEventListener('message', listenOnSave)
})

const getPptData = async () => {
  loading.value = true
  const response = await httpGetPptData(id.value)
  loading.value = false
  if (!response) {
    return
  }
  pptData.value = { ...response }
  headerTitle.value = pptData.value.ppt_name
}

const sendPptToIframe = () => {
  const obj = {
    client: 'client',
    content: pptData.value.content,
    hash: '',
    target: 'init',
    username: userStore.info.name,
  }
  obj.hash = md5(obj.content.substring(0, 100) + obj.client)
  const element = document.getElementById('ppt_ist')
  if (element instanceof HTMLIFrameElement) {
    const ifrWindow = element.contentWindow
    ifrWindow.postMessage(obj, '*')
  }
}
const insertImg = () => {
  const obj = {
    client: 'client',
    content: base64.value,
    hash: '',
    target: 'insertImage',
    username: userStore.info.name,
  }
  obj.hash = md5(obj.content.substring(0, 100) + obj.client)
  const element = document.getElementById('ppt_ist')
  if (element instanceof HTMLIFrameElement) {
    const ifrWindow = element.contentWindow
    ifrWindow.postMessage(obj, '*')
  }
}
const url = ref('')
const loadingImg = ref(false)
const handleGenerateImg = async () => {
  loadingImg.value = true
  try {
    const res = await httpTextToImg({
      prompt: formData.name,
    })
    if (res) {
      url.value = 'data:image/png;base64,' + res.data.binary_data_base64[0]
      base64.value = 'data:image/png;base64,' + res.data.binary_data_base64[0]
    }
  } catch (error) {
  } finally {
    loadingImg.value = false
  }
}
</script>

<template>
  <ppt-header :title="headerTitle">
    <el-tooltip
      class="box-item"
      effect="dark"
      content="AI生成图片"
      placement="left-start"
    >
      <el-icon
        @click="visible = true"
        style="
          font-size: 28px;
          color: #4093ff;
          cursor: pointer;
          margin-right: 20px;
        "
      >
        <AIToImg />
      </el-icon>
    </el-tooltip>
  </ppt-header>
  <div
    style="
      width: 100%;
      height: calc(100% - 50px);
      border: 1px solid #dedede;
      border-top: none;
    "
    v-loading="loading"
  >
    <iframe
      :class="isFullScreen ? 'fixed-ppt' : ''"
      v-if="headerTitle !== ''"
      :src="pptIstUrl"
      allowtransparency="true"
      id="ppt_ist"
      @load="sendPptToIframe"
    ></iframe>
  </div>
  <el-dialog
    title="AI文生图"
    :model-value="visible"
    show-close
    :append-to-body="true"
    @close="visible = false"
    width="500px"
    draggable
  >
    <div
      style="
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 10px;
      "
    >
      <el-image
        style="width: 500px; height: 300px"
        :src="url"
        :zoom-rate="1.2"
        :max-scale="7"
        :min-scale="0.2"
        :initial-index="4"
        fit="fill"
      >
        <template #error>
          <div class="image-slot">
            <!-- <el-icon><icon-picture /></el-icon> -->
             
          </div>
        </template>
      </el-image>
    </div>
    <el-form :model="formData" :rules="rules" ref="submitRef">
      <el-form-item prop="name">
        <el-input
          type="textarea"
          v-model="formData.name"
          placeholder="请输入画面描述，以短句或短语为佳。支持中英文。例如：卷发的世纪少女"
          maxlength="300"
          show-word-limit
          clearable
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="() => {}">取消</el-button>
        <el-button
          type="primary"
          :disabled="!formData.name"
          @click="handleGenerateImg"
          :loading="loadingImg"
          >{{loadingImg ? '生成中...' : '生成图片'}}</el-button
        >
        <el-button type="primary" v-if="url" @click="insertImg">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
#ppt_ist {
  width: 100%;
  height: 100%;
  border: none;
  padding: 0;
  margin: 0;
  background: transparent;
  &.fixed-ppt {
    position: fixed;
    left: 0;
    top: 0;
    width: 100vw;
    height: 100vh;
    z-index: 9999;
  }
}
</style>
